<template>
  <el-row>
    <el-col>
      <el-card class="search-form">
        <el-form ref="searchForm" :rules="rules" class="el-form-col" :model="search" label-width="106px" label-position="left">
          <el-row :gutter="15">
            <el-col :span="6">
              <el-form-item label="盘点仓库:" prop="warehouseId">
                <el-select v-model="search.warehouseId" placeholder="请选择">
                  <el-option v-for="item in warehouseList"
                             :key="item.value"
                             :label="item.text"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="盘点区域:" prop="regionId">
                <tree-select ref="TreeSelect"
                               :data="menuData"
                               placeholder="请选择"
                               v-model="search.regionId"
                ></tree-select>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button type="success" :loading="searchLoading" plain  @click.prevent="searchFunc(search)">搜索
              </el-button>
            </el-col>
            <el-col :span="2">
              <el-button @click.prevent="reset()">重置
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </el-col>
    <el-col :span="24">
      <BasicTable
        ref="BasicTable"
        :columns="columns"
        @setList="setList"
        :createGet="false"
        :page="false"
        :selection="false"
        url="/ms-warehouse-order/inventory/findStorageLocationList"
      >
        <template slot="buttons">
          <el-button type="primary" :disabled="!tableData.length" @click="inventoryFun">开始盘点</el-button>
        </template>
      </BasicTable>
    </el-col>
  </el-row>
</template>

<script>
import {unixTimestampFilter, filterDataBaseDictionary} from '@/filters'
import {arrayToTree, copy, confirm} from '@/utils'
import {getWarehouse} from '@/utils/selectOptions'
export default {
  name: 'warehouseInventoryAdd',
  components: {},
  filters: {
    unixTimestampFilter,
    filterDataBaseDictionary
  },
  data() {
    return {
      searchLoading: false,
      search: {
        warehouseId: '',
        regionId: ''
      },
      menuData: [],
      warehouseList: [],
      tableData: [],
      totalItem: 0,
      params: {
        pageSize: 20,
        pageNum: 1
      },
      rules: {
        warehouseId: [
          { required: true, message: '请选择需要盘点仓库', trigger: 'change' }
        ],
        regionId: [
          { required: true, message: '请选择需要盘点的区域', trigger: 'change' }
        ]
      },
      columns: [
        {
          label: '盘点区域',
          data: 'regionName'
        },
        {
          label: '所属商家',
          data: 'cargoOwnerName'
        },
        {
          label: '产品编号',
          data: 'productNo'
        },
        {
          label: '所属产品',
          data: 'productName'
        },
        {
          label: '包件编号',
          data: 'packageCode'
        },
        {
          label: '包件名称',
          data: 'packageName'
        },
        {
          label: '库存包件数量',
          data: 'locationPackageNum'
        },
        {
          label: '实际包件数量',
          data: 'inventoryAll'
        },
        {
          label: '责任人',
          data: 'dutyMan'
        }
      ]
    }
  },
  created() {
    getWarehouse().then(arr => {
      this.warehouseList = arr || []
      if (this.warehouseList.length === 1) {
        this.search.warehouseId = this.warehouseList[0].value
      }
    })
  },
  watch: {
    'search.warehouseId'(val, oldVal) {
      if (val) {
        this.getMenuData()
        this.tableData = []
        this.$refs.BasicTable.clear()
        this.search.regionId = ''
      }
    }
  },
  methods: {
    reset() {
      this.menuData = []
      this.$refs.searchForm.resetFields()
    },
    searchFunc() {
      this.$refs['searchForm'].validate(valid => {
        if (!valid) { return }
        let params = copy(this.search)
        const basicTable = this.$refs.BasicTable
        this.searchLoading = true
        basicTable.search(params).finally(_ => {
          this.searchLoading = false
        })
      })
    },
    setList(list) {
      this.tableData = list
    },
    getMenuData() {
      this.$ajax.get('/ms-warehouse-order/sorting-maintenance/query-list-warehouse', {werahouseId: this.search.warehouseId}).then(response => {
        if (!response.data) {
          return
        }
        let arr = response.data
        let temp = []
        arr.forEach(v => {
          temp.push({
            value: v.id,
            text: v.storageRegionName,
            pid: v.pId
          })
        })
        this.menuData = arrayToTree(temp, 'value', 'pid', 'children', '0', true) || []
      })
    },
    inventoryFun() {
      this.$refs['searchForm'].validate(valid => {
        if (!valid) { return }
        let obj = {
          inventoryItemList: []
        }
        obj.warehouseId = this.search.warehouseId
        obj.regionId = this.search.regionId
        this.tableData.forEach(item => {
          obj.inventoryItemList.push({
            productId: item.productId,
            cargoOwnerId: item.cargoOwnerId,
            locationId: item.locationId,
            locationPackageId: item.locationPackageId,
            packageId: item.packageId
          })
        })
        this.send(obj)
      })
    },
    send(data) {
      confirm('开始盘点后，所选盘点区域将限制仓库的入库、出库等操作操作影响库存数量，导致库存出错，盘点结束后将自动解锁', '温馨提示', {
        type: 'warning',
        confirmButtonLoading: true,
        confirmCallBack: ({confirmButtonLoadingClose, close}) => {
          this.$ajax.post('/ms-warehouse-order/inventory/saveInventory', data).then(response => {
            if (response.success) {
              close()
              this.searchFunc()
              this.$router.push({path: '/ss-oms/warehouse/inventory/index'})
              setTimeout(_ => {
                this.$message({
                  type: 'success',
                  message: '盘点单已生成！'
                })
              }, 500)
            } else {
              confirmButtonLoadingClose()
            }
          }).finally(_ => {
            confirmButtonLoadingClose()
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
